<template>
  <div>
    <el-card class="box-card">
      <h2>删除角色</h2>
      <el-form :model="roleForm" label-width="120px">
        <el-form-item label="选择角色：">
          <el-select v-model="selectedRole" placeholder="请选择角色">
            <el-option
              v-for="role in roles"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="deleteRole">删除</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleForm: {
        name: '',
        description: '',
        // 如果需要其他角色信息，可以在这里添加
      },
      roles: [],
      selectedRole: null
    };
  },
  created() {
    this.fetchRoles();
  },
  methods: {
    fetchRoles() {
      this.axios.get('/api/role/get')
        .then(response => {
          const result = response.data;
          if (Array.isArray(result.data)) {
            this.roles = result.data;
          } else {
            console.error('Error: Expected an array but got:', result.data);
          }
        })
        .catch(error => {
          console.error('Error fetching roles:', error);
        });
    },
    deleteRole() {
      // 获取选中角色的信息，这里可以根据需要获取角色的其他信息
       const selectedRoleName = this.roles.find(role => role.id === this.selectedRole).name;

      // 发送删除请求，假设删除接口为 '/api/role/delete'
        console.log('要删除的角色ID:', selectedRoleName); // 打印选中角色的ID
      this.axios.delete(`/api/role/delete/${selectedRoleName}`)

        .then(() => {
          this.$message({
            message: '角色删除成功',
            type: 'success'
          });
          // 删除成功后执行其他操作，例如刷新角色列表
          this.fetchRoles();
        })
        .catch(error => {
          console.error('Error deleting role:', error);
          this.$message.error('角色删除失败');
        });
    }
  }
}
</script>

<style scoped>
.box-card {
  margin: auto;
  width: 600px;
}
</style>
